package xian.woniuxy.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import xian.woniuxy.entity.Permission;
import xian.woniuxy.entity.User;
import xian.woniuxy.entity.UserExample;
import xian.woniuxy.mapper.custom.CustomPermissionMapper;
import xian.woniuxy.mapper.custom.CustomRoleMapper;
import xian.woniuxy.mapper.custom.CustomUserMapper;
import xian.woniuxy.service.AuthService;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @author gao
 * @date 2023/07/05 16:00:28
 */
@Service
@Transactional
public class AuthServiceImpl implements AuthService {
    @Autowired
    private CustomUserMapper userMapper;

    @Autowired
    private CustomRoleMapper roleMapper;

    @Autowired
    private CustomPermissionMapper permissionMapper;

    @Override
    public User login(String username, String password) {
        UserExample userExample = new UserExample();
        userExample.or().andUsernameEqualTo(username).andPasswordEqualTo(password);
        List<User> list = userMapper.selectByExample(userExample);
        if (list.size() == 0) {
            throw new RuntimeException("账户或密码错误");
        }
        User user = list.get(0);
        List<Integer> roleIds = roleMapper.findRoleIdsByUserId(user.getUserId());

        Set<Permission> permissions = new HashSet<>();
        for (Integer roleId : roleIds) {
            List<Integer> permissionIds = permissionMapper.findPermissionIdsByRoleId(roleId);
            for (Integer permissionId : permissionIds) {
                Permission permission = permissionMapper.selectByPrimaryKey(permissionId);
                permissions.add(permission);
            }
        }

        user.setPermissions(new ArrayList<>(permissions));

        return user;
    }
}
